package _4TCPChat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;

public class TCPChatServer extends Thread {

	// 服务端口
	final static int PORT = 7777;

	// 窗体的引用
	ChatServerFrame csFrame;
	
	// 保存所有客户端的输出流
	List<OutputStream> outs = new ArrayList<>();

	@Override
	public void run() {
		// 停顿1s 
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		// 1.创建服务Socket
		csFrame.showMsg("开启服务器，端口:" + PORT);
		ServerSocket serSocket = null;
		try {
			serSocket = new ServerSocket(PORT);
		} catch (IOException e) {
			csFrame.showMsg("开启失败，端口已被占用:" + e.getMessage());
			return;
		}

		// 2. 循环监听服务端口，处理客户端的链接
		while (true) 
		{
			csFrame.showMsg("等待客户端连接");
			try {
				Socket s = serSocket.accept();// 会停在这，直到有客户端连接上，继续往下运行
				// 3. 客户端连上了
				String client = s.getInetAddress() + "[" + s.getPort() + "]";
				csFrame.showMsg("客户端连上了" + client);
				// 4. 再开子线程，在子线程接收当前这个客户端的发来的信息
				new Thread(new Runnable() {
					@Override
					public void run() {
						
						try {
							InputStream in = s.getInputStream();
							OutputStream out = s.getOutputStream();
							outs.add(out);
							
							// 先给客户端发送欢迎信息
							out.write("欢迎登陆xxx聊天室".getBytes());
							// 接受客户端发来的信息
							while (true) {
								byte[] buf = new byte[1024];
								int len = in.read(buf); // 会停在这，直到接收到客户端发来的信息
								String msg = new String(buf, 0, len);
								csFrame.showMsg(client + ":" + msg);
								
								// 发给转发给所有已连上的客户端
								for(OutputStream o:outs)
								{
									o.write( (client+":"+msg).getBytes());
								}
								
							}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						
					}
				}).start();

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}
}